package com.wisecoach.gatewayplus.transaction.lockedtx;

import com.wisecoach.gatewayplus.transaction.SubmittedTxProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * {@code @author:} wisecoach
 * {@code @date:} 2023/9/26 上午10:02
 * {@code @version:} 1.0.0
 */


public class LockedTxResource {

    private final ThreadLocal<Integer> stack = new ThreadLocal<>();
    private final ThreadLocal<List<LockedTxContext>> txsToCommit = new ThreadLocal<>();
    private final LockSource lockSource;
    private final SubmittedTxProcessor submittedTxProcessor;

    public LockedTxResource(LockSource lockSource, SubmittedTxProcessor submittedTxProcessor) {
        this.lockSource = lockSource;
        this.submittedTxProcessor = submittedTxProcessor;
    }

    public boolean lock(TxRWSet rwSet) {
        return lockSource.lock(rwSet);
    }

    public void unlock(TxRWSet rwSet) {
        lockSource.unLock(rwSet);
    }


    public void push() {
        if (stack.get() == null) {
            stack.set(0);
        }
        stack.set(stack.get() + 1);
    }

    public void pop() {
        stack.set(stack.get() - 1);
    }

    public Integer getStack() {
        Integer stackDeepth = stack.get();
        if (stackDeepth == null) {
            return 0;
        }
        return stackDeepth;
    }

    public void clearStack() {
        stack.remove();
    }

    public void pushTx(LockedTxContext ctx) {
        List<LockedTxContext> transactions = txsToCommit.get();
        if (transactions == null) {
            transactions = new ArrayList<>();
            txsToCommit.set(transactions);
        }
        transactions.add(ctx);
    }

    public List<LockedTxContext> getTxsToCommit() {
        return txsToCommit.get();
    }

    public void clearTxsToCommit() {
        txsToCommit.remove();
    }

    public void pushTxToConfirm(LockedTxContext ctx) {
        submittedTxProcessor.process(ctx);
    }

}
